package com.xyb.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

@Component
public class OSSUtils {
    // p4java
    private static String group;
    @Value("${config.oss.group}")
    private void setGroup(String group){
        OSSUtils.group = group;
    }
    // 域名
    private static String domainName;
    @Value("${config.oss.domainName}")
    private void setDomainName(String domainName){
        OSSUtils.domainName = domainName;
    }

    /**
     * 国内可以相同
     */
    private static String endpoint;
    @Value("${config.oss.endpoint}")
    public void setEndpoint(String endpoint){
        OSSUtils.endpoint = endpoint;
    }
    /**
     * 子 accessKey
     */
    private static String accessKeyId;
    @Value("${config.oss.accessKeyId}")
    public void setAccessKey(String accessKeyId){
        OSSUtils.accessKeyId = Base64Utils.base64Decode(accessKeyId);
    }
    private static String accessKeySecret;
    @Value("${config.oss.accessKeySecret}")
    public void setAccessKeySecret(String accessKeySecret){
        OSSUtils.accessKeySecret = Base64Utils.base64Decode(accessKeySecret);
    }
    /**
     * bucket名称
     */
    private static String bucket;
    @Value("${config.oss.bucket}")
    public void setBucket(String bucket){
        OSSUtils.bucket = bucket;
    }

    /**
     * 获得 oss客户端
     *
     * @return
     */
    private static OSS getOssClient() {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        return ossClient;
    }

    /**
     * @param filename
     * @param is
     * @return
     */
    public static String upload(String filename, InputStream is) {
        OSS ossClient = getOssClient();
        PutObjectResult result = ossClient.putObject(bucket, filename, is);

        return new StringBuilder()
                .append("https://")
                .append(bucket)
                .append(".")
                .append(domainName)
                .append(".com/")
                .append(filename)
                .toString();
    }


    public static void main(String[] args) {
        OSS ossClient = getOssClient();
        String content = "Hello OSS";
        PutObjectResult result = ossClient.putObject("p4java", "121.png", new ByteArrayInputStream(content.getBytes()));
        ossClient.shutdown();
    }
}
